﻿using System;
using Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace Extensions.Services;

public static class AddCors
{
    public static IServiceCollection AddCorsSetup(this IServiceCollection services)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        var enableCors = Appsettings.app("Startup", "Cors", "Enable").ToBool();
        var allowAny = Appsettings.app("Startup", "Cors", "AllowAny").ToBool();
        var http = Appsettings.app("Startup", "Cors", "Http");
        var policyName = Appsettings.app("Startup", "Cors", "PolicyName");
        // 校验
        if (string.IsNullOrWhiteSpace(policyName)||!enableCors)
        {
            return services;
        }
        services.AddCors(options =>
        {
            options.AddPolicy(policyName,options =>
            {
                options.AllowAnyHeader()
                    .AllowCredentials()
                    .AllowAnyMethod()
                    .SetPreflightMaxAge(TimeSpan.FromHours(1));// 预检过期时间  要设置一下不然会有频繁的预检
                // 所有地址都可以跨域
                if (allowAny)
                {
                    options.SetIsOriginAllowed(_ => true);
                }
                else
                {
                    // 只有配置的地址可以跨域
                    options.WithOrigins(http.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                }
            });
        });
        return services;
    }

    public static IApplicationBuilder UseCorsSetup(this IApplicationBuilder app, IHostEnvironment env)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));
        if (env == null) throw new ArgumentNullException(nameof(env));
        var policyName = Appsettings.app("Startup", "Cors", "PolicyName");
        var enableCors = Appsettings.app("Startup", "Cors", "Enable").ToBool();
        // 生产环境是不开启的
        if (!env.IsDevelopment()||string.IsNullOrWhiteSpace(policyName)||!enableCors)
        {
            return app;
        }
        app.UseCors(policyName);
        return app;
    }
}